package com.wangyb.wework.service.contact;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.wangyb.wework.bo.WwGroupchatAutoPullQueryBo;
import com.wangyb.wework.entity.contact.WwGroupchat;
import com.wangyb.wework.entity.contact.WwGroupchatAutoPull;
import com.wangyb.wework.entity.employee.WwEmployee;
import com.wangyb.wework.exception.CommonException;
import com.wangyb.wework.mapper.contact.WwGroupchatAutoPullMapper;
import com.wangyb.wework.service.IWwEmployeeService;
import com.wangyb.wework.utils.ali.AliyunOssUtils;
import com.wangyb.wework.vo.WwGroupchatAutoPullVo;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自动拉群Service业务层处理
 *
 * @Author: wangyb
 * @Date: 2021/7/13 5:17 下午
 */
@Service
public class WwGroupchatAutoPullServiceImpl extends ServiceImpl<WwGroupchatAutoPullMapper, WwGroupchatAutoPull> implements IWwGroupchatAutoPullService{
	@Autowired
	private IWwGroupchatService iWwGroupchatService;
	@Autowired
	private IWwGroupchatMemberService iWwGroupchatMemberService;
	@Autowired
	private IWwEmployeeService iWwEmployeeService;
	@Autowired
	private IGroupchatAutoPullSyncLogic iGroupchatAutoPullSyncLogic;

	@Override
	public WwGroupchatAutoPullVo queryById(Long id){
		WwGroupchatAutoPullVo vo =  getVoById(id, WwGroupchatAutoPullVo.class);
		List<JSONObject> groupchats = JSONArray.parseArray(vo.getGroupchats(), JSONObject.class);
		Set<Long> groupchatIdSet = groupchats.stream().map(g -> g.getLong("id")).collect(Collectors.toSet());
		if (groupchatIdSet.size() == 0){
			return vo;
		}
		Map<Long, Integer> memberCountMap = iWwGroupchatMemberService.memberCount(groupchatIdSet,1,null,null);
		List<WwGroupchat> groupchatVos = iWwGroupchatService.getBaseMapper().selectBatchIds(groupchatIdSet);
		Map<Long, WwGroupchat> groupchatMap = groupchatVos.stream().collect(Collectors.toMap(WwGroupchat::getId, Function.identity()));
		Set<Long> ownerIdSet = groupchatVos.stream().map(g -> g.getOwnerId()).collect(Collectors.toSet());
		Map<Long, WwEmployee> owerMap = iWwEmployeeService.getBaseMapper().selectBatchIds(ownerIdSet).stream().collect(Collectors.toMap(WwEmployee::getId, Function.identity()));

		groupchats = groupchats.stream().map(json->{
			Long groupchatId = json.getLong("id");
			WwGroupchat groupchat = groupchatMap.get(groupchatId);
			json.put("name",groupchat.getName());
			WwEmployee owner = owerMap.get(groupchat.getOwnerId());
			json.put("owner",owner);
			json.put("memberNum",memberCountMap.get(groupchatId));
			return json;
		}).collect(Collectors.toList());
		vo.setGroupchats(JSONObject.toJSONString(groupchats));
		return vo;
	}

	@Override
	public TableDataInfo<WwGroupchatAutoPullVo> queryPageList(WwGroupchatAutoPullQueryBo bo) {
		PagePlus<WwGroupchatAutoPull, WwGroupchatAutoPullVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), WwGroupchatAutoPullVo.class);
		TableDataInfo<WwGroupchatAutoPullVo> ret = PageUtils.buildDataInfo(result);

		//一次性取出本页面的所有groupchat
		Set<Long> groupchatIdSet = ret.getRows().stream().map(autopull -> {
			List<JSONObject> groupchatsArray = JSON.parseArray(autopull.getGroupchats(), JSONObject.class);
			return groupchatsArray.stream()
				.map(g -> g.getLong("id"))
				.collect(Collectors.toSet());
		}).reduce((longs, longs2) -> {
			longs.addAll(longs2);
			return longs;
		}).get();
		Map<Long, WwGroupchat> groupchatMap = iWwGroupchatService.getBaseMapper().selectBatchIds(groupchatIdSet).stream().collect(Collectors.toMap(WwGroupchat::getId, Function.identity()));
		Map<Long, Integer> memberCountMap = iWwGroupchatMemberService.memberCount(groupchatIdSet, 1, null, null);

		Set<Long> ownerIdSet = groupchatMap.entrySet().stream().map(entry -> entry.getValue().getOwnerId()).collect(Collectors.toSet());
		Map<Long, WwEmployee> employeeMap = iWwEmployeeService.getBaseMapper().selectBatchIds(ownerIdSet).stream().collect(Collectors.toMap(WwEmployee::getId, Function.identity()));

		ret.getRows().stream().forEach(vo->{
			String aliyunUrl = AliyunOssUtils.getUrl(vo.getQrcodeUrl());
			vo.setQrcodeUrl(aliyunUrl);
			List<JSONObject> groupchatsArray = JSON.parseArray(vo.getGroupchats(), JSONObject.class);
			List<JSONObject> groupchatList = groupchatsArray.stream().map(g -> {
				Long groupchatId = g.getLong("id");
				WwGroupchat groupchat = groupchatMap.get(groupchatId);
				g.put("name", groupchat.getName());
				g.put("memberNum",memberCountMap.get(groupchatId));
				g.put("owner",employeeMap.get(groupchat.getOwnerId()));
				return g;
			}).collect(Collectors.toList());
			vo.setGroupchats(JSON.toJSONString(groupchatList));
		});
		return ret;
	}

	@Override
	public List<WwGroupchatAutoPullVo> queryList(WwGroupchatAutoPullQueryBo bo) {
		return listVo(buildQueryWrapper(bo), WwGroupchatAutoPullVo.class);
	}

	private LambdaQueryWrapper<WwGroupchatAutoPull> buildQueryWrapper(WwGroupchatAutoPullQueryBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<WwGroupchatAutoPull> lqw = Wrappers.lambdaQuery();
		lqw.like(StringUtil.isNotBlank(bo.getQrcodeName()), WwGroupchatAutoPull::getQrcodeName, bo.getQrcodeName());
		return lqw;
	}

	@Override
	public Boolean insertByAddBo(WwGroupchatAutoPullVo vo) {
		Long corpId = 1L;
		WwGroupchatAutoPull add = BeanUtil.toBean(vo, WwGroupchatAutoPull.class);
		add.setCorpId(corpId);
		validEntityBeforeSave(add);
		boolean sucess = save(add);
		if (sucess){
			iGroupchatAutoPullSyncLogic.onCreateWxAddContactWayQrcode(add);
		}else {
			throw new CommonException("创建自动拉群失败");
		}
		return sucess;
	}

	@Override
	public Boolean updateByEditBo(WwGroupchatAutoPullVo vo) {
		Long corpId = 1L;
		WwGroupchatAutoPull update = BeanUtil.toBean(vo, WwGroupchatAutoPull.class);
		update.setCorpId(corpId);
		validEntityBeforeSave(update);
		boolean sucess = updateById(update);
		if (sucess){
			update = this.getById(update.getId());
			iGroupchatAutoPullSyncLogic.onUpdateWxAddContactWayQrcode(update);
		}else {
			throw new CommonException("更新自动拉群失败");
		}
		return sucess;
	}

	/**
	 * 保存前的数据校验
	 *
	 * @param entity 实体类数据
	 */
	private void validEntityBeforeSave(WwGroupchatAutoPull entity){
		//TODO 做一些数据校验,如唯一约束
	}

	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if(isValid){
			//TODO 做一些业务上的校验,判断是否需要校验
		}
		return removeByIds(ids);
	}
}
